package com.javastudy.jdkfeature.jdk7.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class WalkingTheDirectoryTree {
    /**
     * 一次性处理的文件字节数
     */
    private static final int ONE_HANDLE_FILE_BYTE_COUNT = 8192;

    /**
     * MD5 算法
     */
    private static final String MD5_ALGORITHM = "MD5";

    /**
     * 无数据的索引值
     */
    private static final int NOT_DATA_INDEX = -1;

    /**
     * 正数符号
     */
    private static final int POSITIVE_SIGN = 1;

    /**
     * 十六进制
     */
    private static final int HEXADECIMAL = 16;

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("F:\\学习文档\\testing");
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toString().endsWith(".pdf")) {
                    String md5 = generateMD5(file.toFile());
                    System.out.println("md5="+md5+";file="+file);
                }
                return FileVisitResult.CONTINUE;
            }
        });

    }

    private static String generateMD5(File file) throws IOException {
        if (!file.isFile())//不是文件
            return null;

//        Files.readAllBytes()
        MessageDigest digest;
        FileInputStream in = null;
        byte buffer[] = new byte[ONE_HANDLE_FILE_BYTE_COUNT];

        byte buffer1[] = Files.readAllBytes(file.toPath());
        int len = buffer1.length;
        try {
            digest = MessageDigest.getInstance(MD5_ALGORITHM);
            in = new FileInputStream(file);

//            while ((len = in.read(buffer)) != NOT_DATA_INDEX) {
//                //digest.update(buffer, 0, len);
//            }
            System.out.println("length="+len);
            digest.update(buffer1, 0, buffer1.length);
            BigInteger bigInteger = new BigInteger(POSITIVE_SIGN, digest.digest());
            return bigInteger.toString(HEXADECIMAL);
        } catch (NoSuchAlgorithmException e) {
//            logger.error(" 生成文件内容的 MD5", e);
            return null;
        } catch (FileNotFoundException e) {
//            logger.error(" 生成文件内容的 MD5", e);
            return null;
        } catch (IOException e) {
//            logger.error(" 生成文件内容的 MD5", e);
            return null;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
//                logger.error("关闭文件", e);
            }
        }
    }
}
